﻿/*
*┌─────────────────────────────────┐
*│　描   述：广告的加载和显示
*│　类   名：InitializeAD.cs 
*│　创  建  人：DD
*│　创建时间：
*│　Copyright(C) 2020 by DD
*└─────────────────────────────────┘
*┌─────────────────────────────────┐
*│　修  改  人：
*│　创建日期：
*└─────────────────────────────────┘
*/

using AnyThinkAds.Api;
using Assets.Scripts.GameManager;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum AdType
{
    MONEY,
    LIVE,
    LV
}

namespace DD
{
    public class InitializeAD : SingleBase<InitializeAD>
    {

        [HideInInspector]
        public AdType adType;

        static BannerCallback bannerCallback;               //Banner回调
        static InterstitalCallback callback;                          //Inter回调
        static ATCallbackListener callbackListener;       //RV回调

        private string AppKey = "79b63e0dbd8c264cf2ef22b84c89cad2";           //appKey
        private string AppID = "a5f644cfaafb4f";                              //appID

        private string BannerID = "b5f644d7354de4";                           //BannerID
        private string InterstitialID = "b5f644d609cb40";                     //插页ID
        private string VideoID = "b5f644d4a1ba25";                            //视频ID

        private void Start( )
        {
            ATSDKAPI.setLogDebug ( true );                             //设置开启广告的log
            ATSDKAPI.initSDK ( AppID , AppKey );//Use your own app_id & app_key here


            //在Start中加载广告
            LoadBannerAd ();

            loadInterstitialAd ();
            loadVideo ();
        }

        #region 关于广告的加载和显示
        /// <summary>
        /// 加载Banner广
        /// </summary>
        public void LoadBannerAd( )
        {
            Debug.Log ( "Banner开始加载" );

            Event.Instance.Banner_Load ();
            if ( bannerCallback == null )
            {
                bannerCallback = new BannerCallback ();
                ATBannerAd.Instance.setListener ( bannerCallback );
            }

            Dictionary<string, object> jsonmap = new Dictionary<string, object>();
            //配置Banner要展示的宽度，高度，是否使用pixel为单位
            ATSize bannerSize = new ATSize(960, 150, true);
            jsonmap.Add ( ATBannerAdLoadingExtra.kATBannerAdLoadingExtraBannerAdSizeStruct , bannerSize );

            ATBannerAd.Instance.loadBannerAd ( BannerID , jsonmap );
            Debug.Log ( "加载完成" );
            ShowBanner ();
        }
        /// <summary>
        /// 显示Banner广告
        /// </summary>
        public void ShowBanner( )
        {
            Debug.Log ( "展示Banner" );
            Event.Instance.Banner_Showed ();
            ATBannerAd.Instance.showBannerAd ( BannerID , ATBannerAdLoadingExtra.kATBannerAdShowingPisitionBottom );
        }

        /// <summary>
        /// 加载插页广告
        /// </summary>
        /// 
        public void loadInterstitialAd( )
        {
            Event.Instance.Inter_Load ();

            if ( callback == null )
            {
                callback = new InterstitalCallback ();
                ATInterstitialAd.Instance.setListener ( callback );
            }

            Dictionary<string, string> jsonmap = new Dictionary<string, string>();
            jsonmap.Add ( "age" , "22" );
            jsonmap.Add ( "sex" , "man" );
            jsonmap.Add ( "interstitial" , "3" );

            ATInterstitialAd.Instance.loadInterstitialAd ( InterstitialID , jsonmap );
        }
        /// <summary>
        /// 显示插页广告
        /// </summary>
        public void showInterstitialAd( )
        {
            Event.Instance.Inter_Showed ();
            ATInterstitialAd.Instance.showInterstitialAd ( InterstitialID );
        }

        /// <summary>
        /// 加载视频广告
        /// </summary>
        public void loadVideo( )
        {
            Event.Instance.Track ( "RV_Load" );

            if ( callbackListener == null )
            {
                callbackListener = new ATCallbackListener ();
                ATRewardedVideo.Instance.setListener ( callbackListener );
            }

            Dictionary<string, string> jsonmap = new Dictionary<string, string>();

            ATRewardedVideo.Instance.loadVideoAd ( VideoID , jsonmap );
        }
        /// <summary>
        /// 展示视频广告
        /// </summary>
        public void showVideo( )
        {
            ATRewardedVideo.Instance.showAd ( VideoID );
        }
        #endregion

        //显示提示
        public void ShowTips( )
        {
            GameObject tipsParent = GameObject.Find("TipsParent");
            GameObject go = GameObject.Instantiate(Resources.Load<GameObject>("Prefabs/Tipss"));
            if ( tipsParent != null && tipsParent.transform.childCount < 1 )
            {
                if ( go != null )
                {
                    go.transform.SetParent ( tipsParent.transform );
                    go.transform.localScale = Vector3.one;
                }
            }
            Destroy ( go , 2.5f );
        }

        #region 广告的回调
        /// <summary>
        /// Banner的回调函数
        /// </summary>
        class BannerCallback : ATBannerAdListener
        {
            public void onAdAutoRefresh(string unitId , ATCallbackInfo callbackInfo)
            {
                //Debug.Log("Developer callback onAdAutoRefresh :" + unitId + "->" + Json.Serialize(callbackInfo.toDictionary()));
                Debug.Log ( "onAdAutoRefresh" );
            }

            public void onAdAutoRefreshFail(string unitId , string code , string message)
            {
                //Debug.Log ( "Developer callback onAdAutoRefreshFail : " + unitId + "--code:" + code + "--msg:" + message );
                Debug.Log ( "onAdAutoRefreshFail" );
            }

            public void onAdClick(string unitId , ATCallbackInfo callbackInfo)
            {
                //Debug.Log("Developer callback onAdClick :" + unitId + "->" + Json.Serialize(callbackInfo.toDictionary()));
                Debug.Log ( "onAdClick" );
            }

            //被关闭时
            public void onAdClose(string unitId)
            {
                InitializeAD.Instance.LoadBannerAd ();
            }

            public void onAdCloseButtonTapped(string unitId , ATCallbackInfo callbackInfo)
            {
                //Debug.Log("Developer callback onAdCloseButtonTapped :" + unitId + "->" + Json.Serialize(callbackInfo.toDictionary()));
                Debug.Log ( "onAdCloseButtonTapped" );
            }

            public void onAdImpress(string unitId , ATCallbackInfo callbackInfo)
            {
                //Debug.Log("Developer callback onAdImpress :" + unitId + "->" + Json.Serialize(callbackInfo.toDictionary()));
                Debug.Log ( "onAdImpress" );
            }

            public void onAdLoad(string unitId)
            {
                Debug.Log ( "Banner加载成功" );
            }

            //加载失败时
            public void onAdLoadFail(string unitId , string code , string message)
            {
                Debug.Log ( "Banner加载失败" + message );
                //如果不是非联网状态
                if ( Application.internetReachability != NetworkReachability.NotReachable )
                {
                    //LoadAD.Instance.LoadBanner ( 20f , InitializeAD.Instance.LoadBannerAd );
                }
            }
        }

        /// <summary>
        /// 插页广告的回调函数
        /// </summary>
        class InterstitalCallback : ATInterstitialAdListener
        {
            public void onInterstitialAdClick(string unitId , ATCallbackInfo callbackInfo)
            {
                Debug.Log ( "Developer callback onInterstitialAdClick :" + unitId );
            }

            //00被关闭时
            public void onInterstitialAdClose(string unitId , ATCallbackInfo callbackInfo)
            {
                //ShowAdMob.Instance.loadInterstitialAd();
                InitializeAD.Instance.loadInterstitialAd ();
                InterMange.RemoteCount ();
                //修改权重
                //ShowInterAd.Instance.RemoveWeight ( 100 );
            }

            public void onInterstitialAdEndPlayingVideo(string unitId , ATCallbackInfo callbackInfo)
            {
                Debug.Log ( "Developer callback onInterstitialAdEndPlayingVideo :" + unitId );
            }

            public void onInterstitialAdFailedToPlayVideo(string unitId , string code , string message)
            {
                Debug.Log ( "Developer callback onInterstitialAdFailedToPlayVideo :" + unitId + "--code:" + code + "--msg:" + message );
            }

            //加载成功
            public void onInterstitialAdLoad(string unitId)
            {
                Debug.Log ( "插页加载成功" );
            }

            public void onInterstitialAdLoadFail(string unitId , string code , string message)
            {
                //ShowAdMob.Instance.StartInter();
                Debug.Log ( "插页加载失败" + message );
            }

            public void onInterstitialAdShow(string unitId , ATCallbackInfo callbackInfo)
            {
                Debug.Log ( "Developer callback onInterstitialAdShow :" + unitId );
            }

            public void onInterstitialAdStartPlayingVideo(string unitId , ATCallbackInfo callbackInfo)
            {
                Debug.Log ( "Developer callback onInterstitialAdStartPlayingVideo :" + unitId );
            }

            //展示失败
            public void onInterstitialAdFailedToShow(string unitId)
            {
                Debug.Log ( "插页显示失败" );
            }

        }

        /// <summary>
        /// 视频广告的回调函数
        /// </summary>
        class ATCallbackListener : ATRewardedVideoListener
        {
            public void onRewardedVideoAdLoaded(string unitId)
            {
                Debug.Log ( "视频加载成功" );
                Event.Instance.Track ( "RV_Loaded" );
            }

            public void onRewardedVideoAdPlayStart(string code , ATCallbackInfo callbackInfo)
            {
                Debug.Log ( "视频开始播放" );
            }

            //加载失败时
            public void onRewardedVideoAdLoadFail(string unitId , string code , string message)
            {
                Debug.Log ( "视频加载失败" + message );

                GameObject tipsParent = GameObject.Find("TipsParent");
               GameObject goRes= Resources.Load<GameObject> ( "Prefabs/Tipss" );
                GameObject go=null;
                if ( goRes )
                {
                    go = GameObject.Instantiate(goRes);
                }

                if ( tipsParent != null && tipsParent.transform.childCount < 1 )
                {
                    if ( go != null )
                    {
                        go.transform.SetParent ( tipsParent.transform );
                        go.transform.localScale = Vector3.one;
                    }
                }
                Destroy ( go , 2.5f );
            }


            public void onRewardedVideoAdPlayEnd(string unitId , ATCallbackInfo callbackInfo)
            {
                Debug.Log ( "视频播放完成" );
                //ShowAdMob.Instance.StartRV();
                //ShowAdMob.Instance.loadVideo();

            }

            //播放失败时
            public void onRewardedVideoAdPlayFail(string unitId , string code , string message)
            {
                //提示
                //LoadAD.Instance.ShowTips ();

                Debug.Log ( "视频播放失败" );
                //ShowAdMob.Instance.StartRV();
                InitializeAD.Instance.loadVideo ();
            }

            //视频呗关闭时
            public void onRewardedVideoAdPlayClosed(string unitId , bool isReward , ATCallbackInfo callbackInfo)
            {
                Debug.Log ( "视频被关闭" );
                InitializeAD.Instance.loadVideo ();
            }

            public void onRewardedVideoAdPlayClicked(string unitId , ATCallbackInfo callbackInfo)
            {
                Debug.Log ( "Developer onRewardVideoAdPlayClicked------" );
            }

            //视频播放完成时
            public void onReward(string unitId , ATCallbackInfo callbackInfo)
            {
                Debug.Log ( "视频播放完成" );
                Event.Instance.RV_Showed ();

                InterMange.SubtractCount ();
                Time.timeScale = 1;

                Debug.Log ( "给予奖励" );

                switch ( InitializeAD.Instance.adType )
                {
                    case AdType.MONEY:

                        int tempShowCount = PlayerPrefs.GetInt("RateCount",0);
                        if ( tempShowCount <= 3 )
                        {
                            tempShowCount++;
                            PlayerPrefs.SetInt ( "RateCount" , tempShowCount );
                            if ( tempShowCount == 2 )
                            {
                                Debug.Log ( "StartShowRate" );
                                GameObject RateUS = GameObject.Find("RateMe").transform.Find("RateMask").gameObject;
                                if ( RateUS != null )
                                {
                                    RateUS.SetActive ( true );
                                }
                            }
                        }

                        Event.Instance.Track ( "SaveMoney_Succ" );
                        GM.GetInstance ().MyAddDiamond ( GiveMoney.giveMoney , true );
                        GameObject go = GameObject.Find("GiveMovey");
                        if ( go != null )
                        {
                            go.SetActive ( false );
                        }
                        break;
                    case AdType.LIVE:
                        Event.Instance.Track ( "Level_Relive" );
                        Debug.Log ( "复活" );
                        break;
                    case AdType.LV:
                        Event.Instance.Track ( "LV_UP" );
                        Debug.Log ( "LV" );
                        GM.GetInstance ().MyAddDiamond ( GiveMoney.giveMoney , true );
                        DialogManager.GetInstance ().Close ( null );
                        //GM.GetInstance ().MyAddDiamond ( GiveMoney.giveMoney , true );
                        break;
                    default:
                        break;
                }
                #endregion


            }
        }
    }
}